﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Boomerang.Common.Crm;
using Boomerang.Common.Configuration;

namespace Boomerang.Management.UIForms
{
    public partial class CrmConnectionForm : Boomerang.Management.UIForms.WizardFormBase
    {
        public CrmConnectionForm()
        {
            InitializeComponent();
        }


        public CrmConnectionForm(string title, WizardFormType type, Organization org)
            : base(title, type,org)
        {
            InitializeComponent();

            logonControlCrm.Options = org.CrmConnectionOptions;

            labelStepTitle.Text = "Configure CRM Connection";
            labelSubTitle.Text = "Use the form below to provide the details to connect to your CRM Organization";            
        }

        protected override bool InternalButtonClick(WizardButtonType wizardButtonType)
        {
            if (wizardButtonType == WizardButtonType.Next || wizardButtonType == WizardButtonType.Finish)
            {
                FormLoading progressForm = new FormLoading("Validating CRM Connection...");
                progressForm.Worker.DoWork += new DoWorkEventHandler(TestConnection);
                progressForm.Worker.RunWorkerAsync(this.logonControlCrm.Options);
                
                progressForm.ShowDialog();

                if (progressForm.Result.Error != null)
                {
                    ExceptionBox.Show(this, progressForm.Result.Error);
                    return false;
                }
                else
                {
                    this.org.CrmConnectionOptions = this.logonControlCrm.Options;
                    return true;
                }

            }

            return true;
        }

        void TestConnection(object sender, DoWorkEventArgs e)
        {
            CrmConnection connection = new CrmConnection((CrmConnectionOptions)e.Argument);

            if (!connection.Test())
                throw new ApplicationException("Connection Unsucessfull");
        }
    }
}
